import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { 
  Post, 
  CreatePostRequest, 
  UpdatePostRequest, 
  PostListResponse,
  QueryParams,
  ApiResponse 
} from '../models/blog.model';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class PostService {
  private readonly BASE_URL = 'http://localhost:8000/api/v1';
  private http = inject(HttpClient);
  private authService = inject(AuthService);

  /**
   * 获取文章列表
   */
  getPosts(params?: QueryParams): Observable<PostListResponse> {
    let httpParams = new HttpParams();
    
    if (params?.page) {
      httpParams = httpParams.set('page', params.page.toString());
    }
    if (params?.size) {
      httpParams = httpParams.set('size', params.size.toString());
    }
    if (params?.q) {
      httpParams = httpParams.set('q', params.q);
    }
    if (params?.category) {
      httpParams = httpParams.set('category', params.category);
    }

    return this.http.get<PostListResponse>(`${this.BASE_URL}/posts`, { params: httpParams });
  }

  /**
   * 获取单篇文章
   */
  getPostById(id: string): Observable<ApiResponse<{ post: Post }>> {
    return this.http.get<ApiResponse<{ post: Post }>>(`${this.BASE_URL}/posts/${id}`);
  }

  /**
   * 创建文章
   */
  createPost(data: CreatePostRequest): Observable<ApiResponse> {
    return this.http.post<ApiResponse>(`${this.BASE_URL}/posts`, data, {
      headers: this.getAuthHeaders()
    });
  }

  /**
   * 更新文章
   */
  updatePost(id: string, data: UpdatePostRequest): Observable<ApiResponse<{ post: Post }>> {
    return this.http.put<ApiResponse<{ post: Post }>>(`${this.BASE_URL}/posts/${id}`, data, {
      headers: this.getAuthHeaders()
    });
  }

  /**
   * 删除文章
   */
  deletePost(id: string): Observable<ApiResponse> {
    return this.http.delete<ApiResponse>(`${this.BASE_URL}/posts/${id}`, {
      headers: this.getAuthHeaders()
    });
  }

  /**
   * 获取认证请求头
   */
  private getAuthHeaders(): HttpHeaders {
    const token = this.authService.getToken();
    return new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    });
  }
} 